#pragma once
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>

class Utils {
    public:
        static int ReadLine(int sock, std::string &out) {
            char ch = 'X';
            while (ch != '\n') {
                ssize_t s = recv(sock, &ch, 1, 0);
                if (s > 0) {
                    if (ch == '\r') {
                        recv(sock, &ch, 1, MSG_PEEK);
                        if (ch == '\n') {
                            recv(sock, &ch, 1, 0);
                        } else {
                            ch = '\n';
                        }
                    }
                    out.push_back(ch);
                } else if (s == 0) {
                    // std::cout << "对端关闭" << std::endl;
                    return -1;
                } else {
                    // std::cout << "读取失败" << std::endl;
                    return -1;
                }
            }
            return out.size();
        }
        
        // 用来把http_request_header中的字符串切分为k:v形势
        static bool CutString(const std::string &line, std::string &sub1_out, std::string &sub2_out, const std::string sep) {
            size_t start = 0;
            size_t pos = line.find(sep, start);
            if (pos != std::string::npos) {
                sub1_out = line.substr(start, pos - start);
                sub2_out = line.substr(pos + sep.size());
                return true;
            } else {
                return false;
            }
        }
};